// coaches-detail.js
var app = getApp()
var req = require('../../utils/reqUtils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    startTime: [
      "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
      "12:00", "12:30", "13:00", "13:30", "14:00", "14:30",
      "15:00", "15:30", "16:00", "16:30", "17:00", "17:30",
      "18:00", "18:30", "19:00", "19:30", "20:00", "20:30",
      "21:00", "21:30", "22:00"
    ],
    courseId: 0,
    classInfo: {},
    endTime: ["请先选择起始时间"],
    selstartTime: "请选择",
    selendTime: "请选择",
    date: [],
    activedateid: 0,
    modalContent: "",
    modalHidden: true,
    startY: 0,
    timedateid: 0,
    course: {},
    coach: {},
    start_date: '',
    end_date: '',
    strat_time: '',
    end_time: '',
    idStr: [],
    duration: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    //获取会员卡编号
    const card_number = options.card_number;
    this.setData({
      card_number: card_number,
    })

    //获取教练信息
    req.post('/coachAndCourseByCardNumber/index', { id: card_number }, 1).then(resT => {
      //设置课程信息及教练信息
      that.setData({
        course: resT.data.course, //获取课程信息
        coach: resT.data.coach //获取绑定教练信息
      })
      console.log("发送请求中……");
      //获取预约信息
      req.post('/get_class_info/index', { 'coach_id': this.data.coach.coach_id, 'course_id': this.data.course.course_id }, 1).then(resC => {
        console.log(1);
        //课程预约时间设置
        // that.setData({
        //   start_date: resC.data.class_info[0].start_date,
        //   end_date: resC.data.class_info[0].end_date,
        //   start_time: resC.data.class_info[0].start_time,
        //   end_time: resC.data.class_info[0].end_time,
        //   duration: resC.data.class_info[0].duration
        // })

        //渲染选择框内容(时间日期，当前日期之后加上7天渲染)。
        var date = [{ id: -1, 'datestr': '时间日期', 'state': 1 }];
        for (var i = 0; i < 7; i++) {
          var onedate = {};
          onedate.id = i;
          onedate.datestr = that.setTime(i, new Date());
          date.push(onedate);
        }
        this.setData({
          date: date
        })

        //获取开始时间和结束时间。
        // var starttimedatetime = (resC.data.class_info[0].start_time).split(':');
        // var endtimedatetime = (resC.data.class_info[0].end_time).split(':');
        // var hours = 0;
        // var startTime = [];

        // var broken = parseInt(((parseInt(endtimedatetime[0]) - parseInt(starttimedatetime[0])) * 60) / resC.data.class_info[0].duration)
        // for (var i = 0; i <= broken; i++) {
        //   //
        //   var hoursDate = parseInt((resC.data.class_info[0].duration * i) / 60);
        //   var minutesDate = (resC.data.class_info[0].duration * i) - 60 * hoursDate;
        //   hours = parseInt(starttimedatetime[0]) + hoursDate;
        //   startTime[i] = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
        // }
        // that.setData({
        //   startTime: startTime,
        //   class_id: resC.data.class_info[0].class_id
        // })
        // console.log(resC.data.class_info[0]['appointment_time']);

        //预约时间
        let appointment_time = resC.data.class_info;
        //休息时间
        let coachRestTime = resC.data.coachRestTime;

        var idStr = [];
        for (var i = 0; i < appointment_time.length; i++) {
          //预约时间年月计算
          let Month = new Date(appointment_time[i]['start_date']).getMonth() + 1;
          let Day = new Date(appointment_time[i]['start_date']).getDate();
          let time = (Month < 10 ? ('0' + Month) : Month) + '-' + (Day < 10 ? ('0' + Day) : Day);
          //预约时间年月时分计算
          let hours = new Date(appointment_time[i]['start_date']).getHours();
          let minutesDate = new Date(appointment_time[i]['start_date']).getMinutes();
          let times = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
          //计算
          let startDateStr = appointment_time[i]['start_date'].replace(' ', 'T');
          let startDate = new Date(startDateStr);
          startDate.setMinutes(startDate.getMinutes() + appointment_time[i].duration);
          let end_times = this.formatDate(startDate)

          let str_d = '';
          let str_t = '';

          //计算出需要标记的横向坐标与纵向坐标
          console.log("date_length", date.length);
          for (var ii = 0; ii < date.length; ii++) {
            //计算标记格颜色横向位置
            if (date[ii].datestr == time) {
              str_d = ii - 1;
            }
            //计算标记格颜色纵向位置 开始时间
            for (var iii = 0; iii < this.data.startTime.length; iii++) {
              //判断开始时间
              if (this.data.startTime[iii] == times) {
                str_t = iii;
                idStr.push(str_t + '-' + str_d);
                //中间涉及的时间。
                for (var iiii = 0; iiii <= ((appointment_time[i]['duration'] / 30)); iiii++) {
                  //判断开始时间
                  iii += 1;
                  idStr.push((iii) + '-' + str_d);
                }
              }
              //判断结束时间
              // let mi = this.data.startTime[iii].split(":");
              // let mi_s = times.split(":");
              // let mi_e = end_times.split(":");
              // console.log('mi_s', mi_s[0]);
              // console.log('mi', mi[0]);
              // console.log('mi_e', mi_e[0]);

              // if (mi_s[0] <= mi[0] && mi_e[0] >= mi[0]) {
              //   console.log('aaa', mi, mi_e);
              //   str_t = iii;
              //   idStr[i] = str_t + '-' + str_d;
              // }
            }


          }
        }
        console.log(coachRestTime);
        //休息时间
        // for (var i = 0; i < coachRestTime.length; i++) {
        //   //休息时间年月计算
        //   let Month = new Date(coachRestTime[i]['start_date']).getMonth() + 1;
        //   let Day = new Date(coachRestTime[i]['start_date']).getDate();
        //   let time = (Month < 10 ? ('0' + Month) : Month) + '-' + (Day < 10 ? ('0' + Day) : Day);

        //   //标记位置和时间
        //   let str_d = '';
        //   let str_t = '';
        //   for (var ii = 0; ii < date.length; ii++) {
        //     //计算标记格颜色横向位置 比对年月
        //     if (date[ii].datestr == time) {
        //       str_d = ii - 1;
        //     }
        //     /**
        //      * 计算标记格颜色纵向位置 比对时分
        //      * 1、拆分出表格中的时间位置。
        //      * 2、休息时间中判断是否表格已经被占用。
        //      */
        //     console.log(date);
        //     let mi = this.data.startTime[ii].datestr.split(":");
        //     let mi_s = coachRestTime[i]['start_time'].split(":");
        //     let mi_e = coachRestTime[i]['end_time'].split(":");

        //     //判断时分
        //     if (mi_s[0] <= mi[0] && mi_e[0] >= mi[0]) {
        //       str_t = ii;
        //     }
        //   }
        //   idStr[i] = str_t + '-' + str_d;
        // }
        that.setData({
          idStr: idStr
        })
        console.log(idStr);
        // console.log(idStr);
        // idStr.forEach(function (itme, index) {
        //   date.forEach(function (itme1, index1) {
        //     if (itme == itme1.datestr) {
        //       console.log('***');
        //     } else {
        //       console.log(itme + '_' + itme1.datestr);
        //     }
        //   })

        //   // console.log(itme);
        // })
        // console.log(idStr);
      })
    })


    //获取会员卡信息
    //  req.post('/card_info/index', {card_number:card_number}, 1).then(res => {

    //   //获取预约信息
    //   req.post('/get_class_info/index', {'coach_id':res.data.card_info[0].coach_id,'course_id':res.data.card_info[0].course_id}, 1).then(resC => { 
    //     console.log(1); 
    // //课程预约时间设置
    // that.setData({
    //       start_date:resC.data.class_info[0].start_date,
    //       end_date:resC.data.class_info[0].end_date,
    //       start_time:resC.data.class_info[0].start_time,
    //       end_time:resC.data.class_info[0].end_time,
    //       duration:resC.data.class_info[0].duration
    //     })

    // //渲染选择框内容(时间日期，当前日期之后加上7天渲染)
    //     var date = [{id:-1,'datestr':'时间日期','state':1}];
    //     for(var i = 0;i<7;i++){
    //       var onedate = {};
    //       onedate.id = i;
    //       onedate.datestr = that.setTime(i,resC.data.class_info[0].start_date);
    //       date.push(onedate);
    //     }

    //  获取开始时间和结束时间。
    //     var starttimedatetime = (resC.data.class_info[0].start_time).split(':');
    //     var endtimedatetime = (resC.data.class_info[0].end_time).split(':');
    //     var hours = 0;
    //     var startTime = [];

    //     var broken = parseInt(((parseInt(endtimedatetime[0]) - parseInt(starttimedatetime[0]))*60)/resC.data.class_info[0].duration)
    //     for(var i = 0;i<=broken;i++){
    //       var hoursDate = parseInt((resC.data.class_info[0].duration*i)/60);
    //       var minutesDate = (resC.data.class_info[0].duration*i) - 60*hoursDate;
    //       hours = parseInt(starttimedatetime[0])+hoursDate;
    //       startTime[i] = (hours < 10 ? ('0' + hours) : hours)+':'+(minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
    //     }
    //     that.setData({
    //       date:date,
    //       startTime: startTime, 
    //       class_id:resC.data.class_info[0].class_id
    //     })         
    //     console.log(resC.data.class_info[0]['appointment_time']);

    //  //预约时间
    //     let appointment_time = resC.data.class_info[0]['appointment_time'];
    //     var idStr = [];
    //     for(var i = 0;i<appointment_time.length;i++){
    //       let Month = new Date(appointment_time[i]['start_date']).getMonth()+1;
    //       let Day = new Date(appointment_time[i]['start_date']).getDate();
    //       let time = (Month < 10 ? ('0' + Month) : Month)+'-'+(Day < 10 ? ('0' + Day) : Day);
    //       let hours = new Date(appointment_time[i]['start_date']).getHours();
    //       let minutesDate = new Date(appointment_time[i]['start_date']).getMinutes();
    //       let times = (hours < 10 ? ('0' + hours) : hours)+':'+(minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
    //       let str_d = '';
    //       let str_t = '';
    //       for(var ii = 0;ii<date.length;ii++){
    //         if(date[ii].datestr == time){
    //           str_d = ii-1
    //         }
    //         if(startTime[ii] == times){
    //           str_t = ii
    //         }
    //       }

    //       idStr[i] = str_t+'-'+str_d;
    //         // console.log(new Date(appointment_time[i]['start_date']).getHours());
    //         // console.log(new Date(appointment_time[i]['start_date']).getMinutes());
    //     }
    //     that.setData({
    //       idStr:idStr
    //     })  
    //     console.log(idStr); 
    //     idStr.forEach(function(itme,index){
    //       date.forEach(function(itme1,index1){
    //         if(itme == itme1.datestr){
    //           console.log('***');  
    //         }else{
    //           console.log(itme+'_'+itme1.datestr);
    //         }
    //       })

    //       // console.log(itme);
    //     })
    //     // console.log(idStr);
    //   })
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  formatDate: function (date) {
    let hours = new Date(date).getHours();
    let minutesDate = new Date(date).getMinutes();
    return (hours < 10 ? ('0' + hours) : hours) + ':' + (minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  initendTimeData: function (startTime) {

  },
  bindPickerstartTimeChange: function (event) {
    var selIterm = this.data.startTime[event.detail.value];
    if (selIterm === "今天无有效时间") {
      return;
    }
    var endTime = this.data.startTime;
    endTime = this.getTimeArray(endTime, selIterm);
    this.setData({
      selstartTime: selIterm,
      endTime: endTime
    })
  },
  bindPickerendTimeChange: function (event) {
    var selIterm = this.data.endTime[event.detail.value];
    if (selIterm === "请先选择起始时间" || selIterm === "今天无有效时间") {
      return;
    }
    this.setData({
      selendTime: selIterm,
    })
  },
  tabClick: function (e) {
    var d = new Date();
    var mon = d.getMonth() + 1;
    var day = d.getDate();
    const curtime = (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    var startTime = [
      "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
      "12:00", "12:30", "13:00", "13:30", "14:00", "14:30",
      "15:00", "15:30", "16:00", "16:30", "17:00", "17:30",
      "18:00", "18:30", "19:00", "19:30", "20:00", "20:30",
      "21:00", "21:30", "22:00"
    ];
    console.log(e.currentTarget.id);
    this.setData({
      selstartTime: "请选择",
      selendTime: "请选择",
      // startTime: startTime,
      endTime: ["请先选择起始时间"],
      activedateid: e.currentTarget.id
    });
  },
  fun_date: function (a) {
    var date1 = new Date();
    var date2 = new Date(date1);
    date2.setDate(date1.getDate() + a);
    var mon = date2.getMonth() + 1;
    var day = date2.getDate();
    var time = (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    if (a === 0) {
      // time += '\n(今)';
    }
    else if (a === 1) {
      // time += '\n(明)';
    }
    return time;
  },
  getTimeArray: function (arr, obj) {
    var index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] > obj) {
        index = i;
        break;
      }
    }
    if (index != -1) {
      arr = arr.slice(index);
    }
    else {
      arr = ["今天无有效时间",];
    }
    return arr;
  },
  appointtap: function () {
    if (this.data.selectTime == "" || this.data.selectDay == "") {
      wx.showToast({
        title: '请先选择正确的预约时段',
        image: '../../images/popup-close.png'
      });
      return;
    }
    const curselDay = this.data.date[this.data.activedateid].datestr;
    this.setData({
      modalContent: '请确认您预定的教练信息\r\n教练: ' + this.data.coach.name + '\r\n预约日期: ' + this.data.selectDay + '\r\n预约时间: ' + this.data.selectStartTime + '--' + this.data.selectEndTime + '\r\n请检查无误后点击确认',
      modalHidden: false
    });
  },
  modalHide: function () {
    this.setData({
      modalContent: '',
      modalHidden: true
    });
    var that = this;
    var date = new Date();

    let start_date = date.getFullYear() + '-' + that.data.selectDay + ' ' + that.data.selectStartTime;
    let end_date = date.getFullYear() + '-' + that.data.selectDay + ' ' + that.data.selectEndTime;

    req.post('/appointment/index', {
      'start_date': start_date,
      'end_date': end_date, 'remarks': '', 'u_id': wx.getStorageSync('userInfo')['u_id'], 'card_number': this.data.card_number
    }, 1).then(res => {
      if (res.data.status == 1) {
        wx.showToast({
          title: '您已成功预约',
          // image: '../../images/popup-close.png'
        });

        setTimeout(function () {
          wx.redirectTo({
            url: "/pages/course-reserve/course-reserve?card_number=" + that.data.card_number,
          })
        }, 2000);

        return;
      }
      console.log(res);
    })
    /**
     * 此处调用预约接口
     */
    console.log(1);
  },
  modalHideCancle: function () {
    this.setData({
      modalContent: '',
      modalHidden: true
    });
  },
  handleTouchStart: function (e) {
    this.data.startY = e.touches[0].clientY;
    // console.log();
  },
  handleTouchMove: function (e) {
    const moveY = e.touches[0].clientY;
    const direction = moveY > this.data.startY ? 'up' : 'down';
    console.log(`用户正在向${direction}滑动${moveY}`);
  },
  handleTouchEnd: function (e) {
    const moveY = e.changedTouches[0].clientY;
    const direction = moveY > this.data.startY ? 'up' : 'down';
    console.log(`用户向${direction}滑动结束${moveY}`);
  },
  subscribeClick: function (e) {
    console.log(e.target.id);
    var Select = (e.target.id).split('-');
    console.log(this.data.date[parseInt(Select[1]) + (this.data.course.duration / 30)])
    //设置课程到期时间
    console.log(this.data.startTime[parseInt(Select[0]) + 1]);
    this.setData({
      timedateid: e.target.id,
      selectDay: this.data.date[parseInt(Select[1]) + 1].datestr,
      selectStartTime: this.data.startTime[parseInt(Select[0])],
      selectEndTime: this.data.startTime[parseInt(Select[0]) + 1],
    })

  },
  courseClick: function (e) {
    let course = this.data.course;
    var that = this;
    course.forEach(item => {
      if (item.class_id == e.currentTarget.id) {
        that.setData({
          start_date: item.start_date,
          end_date: item.end_date,
          start_time: item.start_time,
          end_time: item.end_time,
          duration: item.duration
        })
        var date = [{ id: -1, 'datestr': '时间日期' }];
        for (var i = 0; i < 7; i++) {
          var onedate = {};
          onedate.id = i;
          onedate.datestr = that.setTime(i, item.start_date);
          date.push(onedate);
        }
        var starttimedatetime = (item.start_time).split(':');
        var endtimedatetime = (item.end_time).split(':');
        // const hours = datetime.getHours();
        // const minutes = datetime.getMinutes();
        // const curtime = (hours < 10 ? ('0' + hours) : hours) + ":" + (minutes < 10 ? ('0' + minutes) : minutes);
        // var startTime = that.data.startTime;
        var hours = 0;
        var startTime = [];
        var broken = parseInt(((parseInt(endtimedatetime[0]) - parseInt(starttimedatetime[0])) * 60) / item.duration)
        for (var i = 0; i <= broken; i++) {
          var hoursDate = parseInt((item.duration * i) / 60);
          var minutesDate = (item.duration * i) - 60 * hoursDate;
          hours = parseInt(starttimedatetime[0]) + hoursDate;
          startTime[i] = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
        }
        that.setData({
          date: date,
          startTime: startTime,
          courseId: e.currentTarget.id
        })
        // console.log(1);
      }
    });
  },
  setTime: function (a, time) {
    var date1 = new Date();
    // console.log(date1); 
    var date2 = new Date(date1);
    date2.setDate(date1.getDate() + a);
    var mon = date2.getMonth() + 1;
    var day = date2.getDate();
    var time = (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    return time;
    // console.log(time);
    // return time;
  }
})